You can use function variables and dynamic functions to make your scripting easier!
function WriteHello() { document.write("Hello "); } function WriteWorld() { document.write("World!"); } var functionVariable = null; functionVariable = WriteHello; functionVariable(); functionVariable = WriteWorld; functionVariable();And just to prove that it works:
if(direction == -1) outOfBounds = x < 0; else if(direction == 1) outOfBounds = x > 9; else if(direction == -10) outOfBounds = y < 0; else if(direction == 10) outOfBounds = y > 9; if(outOfBounds) DoSomethingAboutIt();Even if you rewrite this to use a switch() construct, you still have to evaluate the contents of direction everytime through the loop. By using a function variable, you can simply assign the test function before entering the loop:
switch(direction) { case -1 : boundaryTest = TestLeft; break; case 1 : boundaryTest = TestRight; break; case -10: boundaryTest = TestUp; break; case 10 : boundaryTest = TestDown; break; } while(!boundaryTest(x,y)) { // Look at the game board, make some decisions }
<INPUT NAME="button1" TYPE="button" VALUE="Button 1" onClick="CallButtonFunc(this.name)">and the function called looks like
function CallButtonFunc(buttonName) { var functionToCall = buttonName+"_buttonPressed()"; var newFunc = new Function(functionToCall); newFunc(); }While this seems like extra work, it actually makes creating forms easier. You usually have to create a function for each button in a script-enabled form, so there's no more work involved here. What saves you development and maintenance time is that all of the buttons call the same function; in an ordinary form, you'd have to remember create a distinct name for each button and write a unique onClick attribute, too. Using this methodology you only need to remember to create a distinct name.
A second benefit derives from the fact that you can test inside
CallButtonFunc to see if the button function actually exists in
the script. If you've ever been to a website where you've clicked on a
form button, and gotten the Object Expected error dialog, you know
how annoying it is to have a page crash because someone forgot to write
a function. By testing for the existence of the function before it's called,
you can trap the error before it occurs. (The button still won't perform
the task, but at least the page won't crash!)